package com.edu.scnu.controller;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.edu.scnu.element.ElementObj;
import com.edu.scnu.manager.ElementManager;
import com.edu.scnu.manager.GameElement;

/**
 * @apiNote 监听类，用于监听用户的操作
 * @Feature:
 */
public class GameListener implements KeyListener {
    private ElementManager em = ElementManager.getManager();

    /*
     * 通过set集合记录按键状态
     */
    private Set<Integer> set = new HashSet<Integer>();

    @Override
    public void keyTyped(KeyEvent e) {

    }

    /**
     * @apiNote 左37 上38 右39 下40
     *          Feature: 按下按键
     */
    @Override
    public void keyPressed(KeyEvent e) {
        // 记录key=getKeyCode()
        int key = e.getKeyCode();
        // System.out.println(key);
        if (set.contains(key)) {
            return;
        } else {
            set.add(key);
        }
        // 拿到玩家集合
        List<ElementObj> play = em.getElementsByKey(GameElement.PLAY);
        for (ElementObj obj : play) {
            obj.keyClick(true, e.getKeyCode());
        }
    }

    /**
     * Feature: 松开按键
     */
    @Override
    public void keyReleased(KeyEvent e) {
        if (set.contains(e.getKeyCode())) {
            set.remove(e.getKeyCode());
        } else {
            return;
        }
        // 拿到玩家集合
        List<ElementObj> play = em.getElementsByKey(GameElement.PLAY);
        for (ElementObj obj : play) {
            obj.keyClick(false, e.getKeyCode());
            for (Integer elementObj : set) {
                obj.keyClick(true, elementObj);
            }
        }
    }

}
